package main

import (
	"context" // Use "golang.org/x/net/context" for Golang version <= 1.6
	"flag"
	"net/http"
	"strconv"

	"github.com/golang/glog"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"

	gw "graduation/design" // Update
)

var (
	// grpc host
	grpcServerEndpoint = flag.String("grpc-endpoint", "127.0.0.1:8000", "gRPC server endpoint")

	// gateway host
	gateWayHost = flag.String("gateway-endpoint", "127.0.0.1:8001", "gRPC server endpoint")
)

// 支持跨域请求
func CORS (h http.Handler) http.Handler{

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "OPTIONS"{
			header := w.Header()
			header.Add("Access-Control-Allow-Origin","*")
			header.Add("Access-Control-Allow-Credentials","true")
			header.Add("Access-Control-Allow-Headers","token,content-type")
			header.Add("Access-Control-Allow-Methods","POST,GET,DELETE,PATCH,PUT")
			header.Add("Access-Control-Max-Age",strconv.Itoa(60 * 60 * 24 * 3))
			w.Write([]byte("OK"))
		}else{
			header := w.Header()
			header.Add("Access-Control-Allow-Origin","*")
			h.ServeHTTP(w, r)
		}
	})
}


func run() error {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := gw.RegisterGraduationDesignHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
	err = gw.RegisterAdminActionsHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
	err = gw.RegisterGraduationDesignAdminCoreHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
	err = gw.RegisterPermissionServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts)
	if err != nil {
		return err
	}


	return http.ListenAndServe(*gateWayHost, CORS(mux))
}

func main() {
	flag.Parse()
	defer glog.Flush()
	if err := run(); err != nil {
		glog.Fatal(err)
	}
}
